package com.fxf.srb.oss.controller;

import com.fxf.common.exception.BusinessException;
import com.fxf.common.result.R;
import com.fxf.common.result.ResponseEnum;
import com.fxf.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * @author 饭小范
 * @version 1.0
 * @description: TODO
 * @date 2021/5/28 22:30
 */
@RestController
@RequestMapping("/api/oss/file")
@CrossOrigin
@Api("tags = 阿里云文件管理")
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file")MultipartFile file,
            @ApiParam(value = "模块", required = true)
            @RequestParam("module")String module){
        try {
            InputStream inputStream = file.getInputStream();
            //获取文件名
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.upload(inputStream, module, originalFilename);
            log.info(uploadUrl);
            return R.ok().message("文件上传成功").data("url", uploadUrl);
        }catch (Exception e){
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("oss文件删除")
    @PostMapping("/remove")
    public R remove(
            @ApiParam(value = "需要删除的文件路径",required = true)
            @RequestParam("url") String url){

        fileService.removeFile(url);
        return R.ok().message("删除成功");

    }
}
